package com.zhong.wechat.controller;

import com.zhong.wechat.handler.WeChatMegHandler;
import com.zhong.wechat.handler.WeChatMsgFactory;
import com.zhong.wechat.untils.MessageUtil;
import com.zhong.wechat.untils.SHA1;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/wechat")
public class CallBackController {

    private static final String TOKEN = "9832bdfsf8";

    @Resource
    private WeChatMsgFactory weChatMsgFactory;

    private static final String CACHE_KEY_SEPARATOR = ".";


    /**
     * 回调消息校验
     */
    @GetMapping("/callback")
    public String callback(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce, @RequestParam(value = "echostr",required = false) String echostr) {
        log.info("get 验签请求参数  signature:{}, timestamp:{}, nonce:{}, echostr:{}", signature, timestamp, nonce, echostr);
        String sha1Str = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
        if (signature.equals(sha1Str)) {
            return echostr;
        }
        return "unknown";
    }

    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callbackPost(@RequestBody String requestBody, @RequestParam(value = "msg_signature", required = false) String msgSignature,
                               @RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
                               @RequestParam("nonce") String nonce, @RequestParam(value = "echostr",required = false) String echostr) {
        log.info("post 接收微信公众号消息 requestBody:{}, msgSignature:{}, signature:{}, timestamp:{}, nonce:{}, echostr:{}",requestBody, msgSignature,signature, timestamp, nonce, echostr);
        Map<String, String> msgMap = MessageUtil.parseXml(requestBody);
        //根据对应事件做出响应
        String msgType = msgMap.get("MsgType");
        String event = msgMap.get("Event") == null ? "" : CACHE_KEY_SEPARATOR + msgMap.get("Event");
        String msgTypeKey = msgType + event;
        WeChatMegHandler weChatMegHandler = weChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if(Objects.isNull(weChatMegHandler)){
            return "unknown";
        }
        String replyContent = weChatMegHandler.dealMsg(msgMap);
        log.info("replyContent: {}",replyContent);
        return replyContent;
    }


}
